package com.bootdo.check.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;

import org.bytedeco.javacpp.opencv_core.KeyPointVector;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_xfeatures2d.SURF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import com.bootdo.check.service.ColorLogo;
import com.bootdo.common.utils.OpenCVUtilsJava;

/**
 * 
 * @author ke
 *
 */
@Component(ColorLogo.BLACK)
public class LogoBlack implements ColorLogo{

	private static final Logger logger = LoggerFactory.getLogger(LogoBlack.class);

	private LogoBlack() {
	}

	private Mat blackLogo;
	private KeyPointVector blackPoints = new KeyPointVector();
	private Mat blackDescriptors = new Mat();

	@PostConstruct
	private void init() {
		try (SURF surf = SURF.create(100d, 8, 6, false, true);) {
			File logoFile = getLogoFile();
			logger.info("logoFilePath=>{}", logoFile.getAbsolutePath());
			blackLogo = OpenCVUtilsJava.loadOrExit(logoFile, 1);
			surf.detect(blackLogo, blackPoints);
			surf.compute(blackLogo, blackPoints, blackDescriptors);
		} catch (Exception e) {
			logger.error("logo模板初始化失败=>" + e.getMessage(), e);
			System.exit(-1);
		}
	}

	private File getLogoFile() {
		ClassPathResource classPathResource = new ClassPathResource("detection/logo_black.jpg");
		try {
			return classPathResource.getFile();
		} catch (Exception e) {
			String path = System.getProperty("java.io.tmpdir") + System.currentTimeMillis() + "kxlogoblacktmp.jpg";
			try (InputStream is = classPathResource.getInputStream();
					FileOutputStream fos = new FileOutputStream(path)) {
				byte[] b = new byte[1024];
				while (is.read(b) != -1) {
					fos.write(b);
				}
			} catch (IOException e1) {
				logger.error("logo提取失败=>" + e.getMessage(), e);
				System.exit(-1);
			}
			return new File(path);
		}

	}

	@Override
	public Mat getLogo() {
		return blackLogo;
	}

	public KeyPointVector getPoints() {
		return blackPoints;
	}

	@Override
	public Mat getDescriptors() {
		return blackDescriptors;
	}
}
